#pragma once
#include "Socket.hpp"
#include "Protocal.hpp"
using namespace std;

enum
{
    DIV_ZERO = 1,
    MOD_ZERO,
    OTHER_OPER
};

// 服务器计算类：实现核心计算逻辑和错误处理
class ServerCal
{
public:
    ServerCal()
    {
    }
    Response calculatorHelper(const Request &req)
    {
        Response resp(0, 0);
        switch (req.op)
        {
            case '+':
                resp._result = req.x + req.y;
                break;
            case '-':
                resp._result = req.x - req.y;
                break;
            case '*':
                resp._result = req.x * req.y;
                break;
            case '/':
                {
                    if (req.y == 0)
                        resp._code = DIV_ZERO;
                    else
                        resp._result = req.x / req.y;
                }
                break;
            case '%':
                {
                    if (req.y == 0)
                        resp._code = MOD_ZERO;
                    else
                        resp._result = req.x % req.y;
                }
                break;
            default:
                resp._code = OTHER_OPER;
                break;
        }
        return resp;
    }
    string calculator(string &package)
    {
        string content;
        bool r = decode(package, &content); // content = "10+20"
        if (!r)
            return "";
        Request req;
        r = req.deserialize(content); // "10+20" ---> x=10 op=+ y=20
        if (!r)
            return "";

        content = "";
        Response resp = calculatorHelper(req); // result = 30  code = 0
        resp.serialize(&content);              // "30 0"
        content = encode(content);             // content = "len""\n""30 0""\n"

        return content;
    }
    ~ServerCal()
    {
    }
};